package csmaster

import (
	"brickyard/util"
	"net/url"
)

type Clerk struct {
	Master string
}

func NewClerk(master string) *Clerk {
	ck := new(Clerk)
	ck.Master = master
	return ck
}

//returns a json string containing account id, auth token etc.
func (ck *Clerk) AddAccount(name, level string) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("level", level)
	return ck.postToMaster("regaccount", values)
}

//returns a json of containerid
func (ck *Clerk) AllocBucket(name, level string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("level", level)
	values.Add("authpair", strconv.FormatUint(authPair, 16))
	return ck.postToMaster("allocbucket", values)
}

func (ck *Clerk) StatBucket(name string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("authpair", strconv.FormatUint(authPair, 16))

	return ck.postToMaster("statbucket", values)
}

func (ck *Clerk) DeleteBucket(name string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("authpair", strconv.FormatUint(authPair, 16))

	return ck.postToMaster("delbucket", values)
}

func (ck *Clerk) ResizeBucket(name string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("authpair", strconv.FormatUint(authPair, 16))

	return ck.postToMaster("resizebucket", values)
}

func (ck *Clerk) StatAccount(name string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("name", name)
	values.Add("authpair", strconv.FormatUint(authPair, 16))

	return ck.postToMaster("statccount", values)
}

func (ck *Clerk) ListBuckets(account string, authPair uint64) (string, error) {
	values := make(url.Values)
	values.Add("account", name)
	values.Add("authpair", strconv.FormatUint(authPair, 16))

	return ck.postToMaster("listbuckets", values)
}

func (ck *Clerk) postToMaster(subdomain string, values url.Values) (string, error) {
	jsonBlob, errPost := util.Post("http://"+ck.Master+"/"+subdomain, values)
	if errPost != nil {
		return "", errPost
	}

	var jsonStr string
	errUnm := json.Unmarshal(jsonBlob, &jsonStr)
	if errUnm != nil {
		return "", errUnm
	}

	return jsonStr, nil
}
